package com.ruoyi.common.utils.ps;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 原图分配
 */
public class ImageFolderSplitter {

    // 支持的图片格式
    private static final List<String> IMAGE_EXTENSIONS = Arrays.asList(
            "jpg", "jpeg", "png", "gif", "bmp", "tiff", "webp"
    );

    public static void main(String[] args) {
        // 配置参数
        String sourceDir = "D:\\BaiduNetdiskDownload\\码诚"; // 源图片文件夹路径
        String outputDir = "D:\\BaiduNetdiskDownload\\p30W数据";     // 输出文件夹路径

        try {
            splitImagesIntoFolders(sourceDir, outputDir);
            System.out.println("处理完成！");
        } catch (IOException e) {
            System.err.println("处理过程中发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }

    public static void splitImagesIntoFolders(String sourceDir, String outputDir) throws IOException {
        // 获取源文件夹中的所有图片文件
        File sourceFolder = new File(sourceDir);
        File[] allFiles = sourceFolder.listFiles();

        if (allFiles == null || allFiles.length == 0) {
            System.out.println("源文件夹中没有文件");
            return;
        }

        // 过滤出图片文件
        List<File> imageFiles = new ArrayList<>();
        for (File file : allFiles) {
            if (file.isFile() && isImageFile(file)) {
                imageFiles.add(file);
            }
        }

        if (imageFiles.isEmpty()) {
            System.out.println("源文件夹中没有图片文件");
            return;
        }

        System.out.println("找到 " + imageFiles.size() + " 张图片");

        // 创建输出目录
        File outputFolder = new File(outputDir);
        if (!outputFolder.exists()) {
            outputFolder.mkdirs();
        }

        int batchSize = 500;
        int totalBatches = (int) Math.ceil((double) imageFiles.size() / batchSize);

        // 处理每批图片
        for (int batch = 0; batch < totalBatches; batch++) {
            int startIndex = batch * batchSize;
            int endIndex = Math.min(startIndex + batchSize, imageFiles.size());

            // 创建批次文件夹
            String batchFolderName = startIndex + "-" + (endIndex - 1);
            File batchFolder = new File(outputDir, batchFolderName);
            if (!batchFolder.exists()) {
                batchFolder.mkdirs();
            }

            System.out.println("处理文件夹: " + batchFolderName);

            // 为每个批次创建Excel工作簿
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("图片列表");

            // 创建表头
            Row headerRow = sheet.createRow(0);
            headerRow.createCell(0).setCellValue("原文件名");
            headerRow.createCell(1).setCellValue("目标文件夹");
            headerRow.createCell(2).setCellValue("新文件名(无后缀)");

            int rowNum = 1;

            // 复制图片到批次文件夹并记录到Excel
            for (int i = startIndex; i < endIndex; i++) {
                File imageFile = imageFiles.get(i);
                String fileNameWithoutExt = getFileNameWithoutExtension(imageFile.getName());
                String fileExtension = getFileExtension(imageFile.getName());

                // 构建目标文件名
                String newFileName = fileNameWithoutExt + "." + fileExtension;
                File destFile = new File(batchFolder, newFileName);

                // 复制文件
                Files.copy(imageFile.toPath(), destFile.toPath(), StandardCopyOption.REPLACE_EXISTING);

                // 添加到Excel
                Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(imageFile.getName());
                row.createCell(1).setCellValue(batchFolderName);
                row.createCell(2).setCellValue(fileNameWithoutExt);
            }

            // 调整列宽
            for (int i = 0; i < 3; i++) {
                sheet.autoSizeColumn(i);
            }

            // 保存Excel文件到批次文件夹
            String excelFileName = batchFolderName + "_image_list.xlsx";
            File excelFile = new File(batchFolder, excelFileName);
            try (FileOutputStream outputStream = new FileOutputStream(excelFile)) {
                workbook.write(outputStream);
            }

            workbook.close();
            System.out.println("已生成Excel文件: " + excelFileName);
        }
    }

    // 检查文件是否为图片
    private static boolean isImageFile(File file) {
        String fileName = file.getName().toLowerCase();
        for (String ext : IMAGE_EXTENSIONS) {
            if (fileName.endsWith("." + ext)) {
                return true;
            }
        }
        return false;
    }

    // 获取文件名（不含扩展名）
    private static String getFileNameWithoutExtension(String fileName) {
        int dotIndex = fileName.lastIndexOf('.');
        if (dotIndex > 0) {
            return fileName.substring(0, dotIndex);
        }
        return fileName;
    }

    // 获取文件扩展名
    private static String getFileExtension(String fileName) {
        int dotIndex = fileName.lastIndexOf('.');
        if (dotIndex > 0) {
            return fileName.substring(dotIndex + 1);
        }
        return "";
    }
}
